using System;
using System.Collections.Generic;
using System.Text;
using ConnectionTypes;
using System.Threading;

namespace sla
{
    class ConnectionsManager
    {

        SignalsManager slaSignalsManagerRef;
        tcpServer myServer = new tcpServer(4444);
        
       
        public ConnectionsManager (SignalsManager slaSignalManager)
        
        {
            slaSignalsManagerRef = slaSignalManager;
            Thread serverConnectionThread = new Thread(new ThreadStart(handleOneClient));
            serverConnectionThread.Start();          

        }

        void handleOneClient()
        {
            int timeStamp = new int();
            int signals = new int();
            uint rxDataLength = new uint();
            byte[] rxBuffer = new byte[1000];
            myServer.createConnection();
            for (int z=0;z<2;z++)
            {
                // Read the length header
                myServer.receive(ref rxBuffer, 4);
                rxDataLength = (uint)byteToInt32(rxBuffer, 0);
                myServer.receive(ref rxBuffer, /* 8*20 */(int)rxDataLength);
                rxDataLength = rxDataLength / 8;
                for (uint i = 0; i < rxDataLength; i++)
                {
                    timeStamp = byteToInt32(rxBuffer, i * 8);
                    signals = byteToInt32(rxBuffer, (i * 8) + 4);
                    slaSignalsManagerRef.processNewCapture(timeStamp, signals);
                    slaSignalsManagerRef.RefreshAllSignal(Signal.TimePerDivisionInMicroSeconds, 0);
                }               
            }

        }

        int byteToInt32(byte[] rawInt,uint offset)
        {
            int result = new int();
            result = (int)(rawInt[offset]);
            result |= (int)(rawInt[offset+1] << 8);
            result |= (int)(rawInt[offset+2] << 16);
            result |= (int)(rawInt[offset+3] << 24);
            return result;
        }
        
    }
}
